package com.feinno.urcs.group.siptask;

import com.feinno.urcs.group.servlet.GroupMemberDialog;
import com.feinno.urcs.group.servlet.GroupMemberDialogHasOffline;
import com.feinno.urcs.group.servlet.GroupServlet;
import com.feinno.urcs.group.siptask.task.GroupByeArgs;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.task.DedicatedTask;
import org.helium.framework.task.DedicatedTaskContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Lei Gao on 5/16/15.
 */
@TaskImplementation(event = GroupTaskEvents.GROUP_BYE)
public class GroupByeTask implements DedicatedTask<GroupByeArgs> {
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupByeTask.class);

	@FieldSetter("group:GroupServlet")
	private GroupServlet servlet;

	public GroupByeTask() {

	}

	public GroupByeTask(GroupServlet servlet) {
		this.servlet = servlet;
	}

	@Override
	public void processTask(DedicatedTaskContext ctx, GroupByeArgs args) {
		GroupMemberDialog dialog = (GroupMemberDialog) ctx.getSession(GroupServlet.TASK_CONTEXT_NAME);
		LOGGER.info(String.format("groupByetask args=%s", args.toJsonObject()));
		if (args.isOnlyClean()) {
			LOGGER.info(String.format("clean Dialog mobile=%s GroupId=%s msrp=%s ", dialog.getMemberMobile(), dialog.getGroupId(), dialog.getRemoteMsrpPath()));
			dialog.closeMsrp();
			dialog.closeSipSession();
			dialog.setClean(true);
			ctx.putSession(GroupServlet.TASK_CONTEXT_NAME, dialog);
			ctx.setTaskRunnable();
			return;
		}

		if (dialog != null) {
			try {
				LOGGER.info(String.format("byeDialog  args=%s Dialog mobile=%s GroupId=%s msrp=%s ", args.toJsonObject(), dialog.getMemberMobile(), dialog.getGroupId(), dialog.getRemoteMsrpPath()));
				servlet.byeDialog(ctx, dialog, args);
			} catch (Exception e) {
				LOGGER.error("processTask  error args=" + args.toJsonObject().toString(), e);
			}
		} else {
			LOGGER.warn(String.format("GroupBye Task dialog is null, args : %s ", args));
		}
		ctx.setTaskRunnable();
	}


	@Override
	public void processTaskRemoved(DedicatedTaskContext ctx) {
		servlet.close(ctx);
	}
}
